package cn.wyl.org.controller;

import cn.wyl.basic.dto.ShopDto;
import cn.wyl.basic.exception.BusinessException;
import cn.wyl.basic.util.AxiousResult;
import cn.wyl.basic.util.ExcelUtils;
import cn.wyl.basic.util.PageList;
import cn.wyl.org.domain.Shop;
import cn.wyl.org.domain.ShopAuditLog;
import cn.wyl.org.query.ShopQuery;
import cn.wyl.org.service.ShopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/shop")
/*swagger:打在Controller对Controller做描述*/
@Api(value = "店铺的API",description="店铺相关的CRUD功能")
public class ShopController {
    @Autowired
    private ShopService service;
    /**
     * 查询单个对象
     * 请求地址：  http://localhost/shop/1
     * @param id
     * @return
     */
    /*等价于：@RequestMapping( value=?,method = {RequestMethod.GET}   )*/
    @GetMapping("/{id}")
    /*swagger:打在方法上，对方法做描述*/
    @ApiOperation(value = "通过ID查询" )
    /*swagger:打在方法上，对方法参数做描述约定.paramType = "path"：从url路径中解析参数id,dataType = "Long"，参数类型为Long*/
    @ApiImplicitParam(name="id",value = "店铺id",required = true,paramType = "path",dataType = "Long")
    public Shop loadById(
            /*swagger:打在参数前，对参数做描述*/
            //@ApiParam(name="编号",required = true)
            @PathVariable("id") Long id)
    {
        return service.loadById(id);
    }

    /**
     * 查询所有对象
     *请求地址：  http://localhost/shop
     * @return
     */
    @GetMapping
    public List<Shop> loadAll() {
        return service.loadAll();
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    /*等价于：@RequestMapping( value=?, method = {RequestMethod.DELETE}   )
    * @PathVariable从路径中获取变量
    * 请求参数携带在地址栏里默认get请求
    * */
    public AxiousResult delete(@PathVariable("id") Long id) {
        try {
            if (service.loadById(id)!=null) {
                service.remove(id);
                return new AxiousResult();
            }
            else {
                return new AxiousResult(false, "删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new AxiousResult(false, "删除失败");
        }

    }

    /**
     * 添加或修改
     * @param shop
     * @return
     */
    @PutMapping
    /*@RequestBody从请求体【请求数据包中】中获取数据 默认post请求
    * */
    public AxiousResult addOrUpdate(@RequestBody Shop shop){
        try{
            if (shop.getId()==null){
            service.save(shop);
            }else{
               if (service.loadById(shop.getId())!=null){
                   service.update(shop);
               }else{
                   return new AxiousResult(false, "操作失败");
               }

            }
            return new AxiousResult();
        } catch (Exception e){
            e.printStackTrace();
            return new AxiousResult(false, "操作失败");
        }

    }

    /**
     * 分页查询或高级查询  请求地址：  http://localhost/shop
     * @param
     * @return
     */
    @PostMapping
    /*@RequestBody从请求体【请求数据包中】中获取数据 默认post请求
     * */
    public PageList<Shop> queryPage(@RequestBody ShopQuery query){

        return service.queryPage(query);
    }

    // 前端请求体传过来[1,3]
    @PatchMapping
    public AxiousResult patchDel(@RequestBody List<Long> ids) {
        try {
            System.out.println(ids);
            service.patchDel(ids);
            return new AxiousResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AxiousResult(false, "删除失败");
        }

    }

    //    处理前端店铺注册的请求  /shop/settlement
    @PostMapping("/settlement")
    /*@RequestBody从请求体【请求数据包中】中获取数据 默认post请求
     * */
    public AxiousResult settlement(@RequestBody Shop shop){


        try {
             service.settlement(shop);
            return new AxiousResult();
        } catch (BusinessException e) {//业务异常捕获
            e.printStackTrace();
            return new AxiousResult(false, e.getMessage());
        } catch (Exception e) { //500
            e.printStackTrace();
            return new AxiousResult(false,"系统异常,请稍后重试!");
        }
    }

    // 处理前端店铺审核通过的请求 /audit/pass
    @PostMapping("/audit/pass")
    public AxiousResult passShop(@RequestBody ShopAuditLog log){
        System.out.println(log);

        try {
            //通过店铺审核日志
            service.pass(log);
            return new AxiousResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AxiousResult(false,"审核通过发生异常");
        }
    }

    //  处理前端店铺审核驳回的请求  /audit/reject
    @PostMapping("/audit/reject")
    public AxiousResult rejectShop(@RequestBody ShopAuditLog log){


        try {
            //驳回店铺审核日志
            service.reject(log);
            return new AxiousResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AxiousResult(false,"审核驳回发生异常");
        }
    }
    //处理前端导出shop excel的请求
    //请求路径http://localhost:8080/shop/export  隐式请求参数HttpServletResponse response 请求方式get

    @GetMapping("/export/{token}")
    public void export(@PathVariable("token")String token,HttpServletResponse response){
        try {
            List<Shop> shops = service.loadAll();
            /*exportExcel(List<?> list,      导出的集合
                    String title,            标题
                    String sheetName,        表名
                    Class<?> pojoClass,      导出表对应的domain的class文件
                    String fileName,         导出设置的文件名
                    HttpServletResponse response) 响应
             */
            // 通过HttpServletResponse response响应给前端

            ExcelUtils.exportExcel(shops, null, "店铺信息", Shop.class, "shop.xlsx", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 处理前端导入excel表的请求
    // 请求路径http://localhost:8080/shop/importExcel  请求参数name="file" 请求方式post
    @PostMapping("/importExcel")
    public void importExcel(@RequestPart(value = "file",required = true)MultipartFile file){
        /*List<T> importExcel(MultipartFile file, 从前端接收的导入的文件，必须和domain对应
                Integer titleRows,                标题占用的行数
                Integer headerRows,               列名占用的行数
                Class<T> pojoClass)               对应的domain
        */
        List<Shop> list = ExcelUtils.importExcel(file, 0, 1, Shop.class);
        System.out.println("导入数据一共【"+list.size()+"】行");
        for (Shop shop:list) {
            System.out.println(shop);
        }
        //保存到数据库中[自己实现，提示：动态sql 批量插入]
    }
    //接收前端的请求/shop/echarts，返回List<ShopDto> ，ShopDto封装了state,countNum属性
    @GetMapping("/echarts")
    public List<ShopDto> echartsData(){
        List<ShopDto> shopDtos = service.getCountByState();
        return shopDtos;
    }







}
